import 'dart:ui' as ui;
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_bilibili/core/I18n/str_res_keys.dart';
import 'package:flutter_bilibili/core/event_bus/event_bus.dart';
import 'package:flutter_bilibili/core/shared_preferences/bilibili_shared_preference.dart';
import 'package:flutter_bilibili/core/shared_preferences/shared_preference_util.dart';
import 'package:flutter_bilibili/ui/pages/charts/charts.dart';
import 'package:flutter_bilibili/ui/pages/publish/publish.dart';
import 'package:flutter_bilibili/ui/shared/app_theme.dart';
import 'package:flutter_bilibili/ui/shared/image_assets.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_speed_dial/flutter_speed_dial.dart';
import 'package:get/get.dart';
import 'package:jpush_flutter/jpush_flutter.dart';
import 'package:permission_handler/permission_handler.dart';
import '../../../core/service/utils/constant.dart';
import '../../shared/platform_judge.dart';
import '../push/push.dart';
import 'initialize_main.dart';

class HYMainScreen extends StatefulWidget {
  ///起始路由
  static const String routeName = "/";

  const HYMainScreen({Key? key}) : super(key: key);

  @override
  State<HYMainScreen> createState() => _HYMainScreenState();
}

class _HYMainScreenState extends State<HYMainScreen> {
  int _currentIndex = 0;

  ///极光推送
  JPush jPush = JPush();

  @override
  void initState() {
    mineEventBus.on<int>().listen((event) {
      ///接收事件总线传来的数据，主要用于跳转至“我的”页面
      setState(() {
        _currentIndex = event;
      });
    });

    if (!kIsWeb) {
      if (PlatformJudge.platformJudgeIsPhone()) {
        ///获取多个权限
        requestPermissions();
      }
    }

    ///初始化极光推送
    initJPush();

    super.initState();
  }

  ///权限获取
  void requestPermissions() async {
    Map<Permission, PermissionStatus> statuses = await [
      Permission.phone,
      Permission.storage,
      Permission.location,
      Permission.notification,
    ].request();
  }

  Future<void> initJPush() async {
    try {
      jPush.addEventHandler(
          onReceiveNotification: (Map<String, dynamic> message) async {
        print("flutter onReceiveNotification: $message");
      }, onOpenNotification: (Map<String, dynamic> message) async {
        print("flutter onOpenNotification: $message");
      }, onReceiveMessage: (Map<String, dynamic> message) async {
        print("flutter onReceiveMessage: $message");
      }, onReceiveNotificationAuthorization:
              (Map<String, dynamic> message) async {
        print("flutter onReceiveNotificationAuthorization: $message");
      });
    } on PlatformException {}

    jPush.setup(
      appKey: Constant.jPushAppKey, //你自己应用的 AppKey
      channel: "flutter_jPush",
      production: false,
      debug: true,
    );
    jPush.applyPushAuthority(
        const NotificationSettingsIOS(sound: true, alert: true, badge: true));
    jPush.getRegistrationID().then((rid) {
      print("flutter get registration id : $rid");
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: IndexedStack(
        ///显示哪一个页面
        index: _currentIndex,

        ///显示那些页面
        children: mainIndexStackPages,
      ),

      ///底部导航栏
      bottomNavigationBar: BottomNavigationBar(
        ///选中时字体大小
        selectedFontSize: HYAppTheme.xxSmallFontSize,

        ///未选中时字体大小
        unselectedFontSize: HYAppTheme.xxSmallFontSize,

        ///选中时字体颜色
        selectedItemColor: HYAppTheme.norMainThemeColors,

        ///显示label标签，而不是隐藏label
        type: BottomNavigationBarType.fixed,

        ///当前显示的页面
        currentIndex: _currentIndex,

        ///底部按钮
        items: [
          buildBottomNavigationBarItem(SR.home.tr.toUpperCase(), "home"),
          buildBottomNavigationBarItem(SR.dynamic.tr.toUpperCase(), "dynamic"),
          buildBottomNavigationBarCenterBarItem(),
          buildBottomNavigationBarItem(SR.mall.tr.toUpperCase(), "vip"),
          buildBottomNavigationBarItem(SR.mine.tr.toUpperCase(), "mine"),
        ],
        onTap: (index) {
          ///发布界面
          if (index == 2) {
            Navigator.of(context).pushNamed(HYPublishScreen.routeName);
          } else {
            setState(() {
              _currentIndex = index;
            });
          }
        },
      ),
      floatingActionButton: SpeedDial(
        icon: Icons.star_rate_sharp,
        backgroundColor: HYAppTheme.norMainThemeColors,
        children: [
          SpeedDialChild(
            onTap: () {
              Navigator.of(context).pushNamed(HYChartScreen.routeName);
            },
            backgroundColor: Colors.white,
            label: '统计',
            child: ImageIcon(
              AssetImage(ImageAssets.chartsCustomPNG),
              size: 10.h,
            ),
          ),
          SpeedDialChild(
            backgroundColor: Colors.white,
            onTap: () {
              if (PlatformJudge.platformJudgeIsPhone()) {
                Navigator.of(context).pushNamed(HYPushScreen.routeName);
              } else {
                print("网页和桌面端暂无推送");
              }
            },
            label: '推送',
            child: Icon(
              Icons.announcement_sharp,
              size: 10.h,
            ),
          ),
          SpeedDialChild(
            backgroundColor: Colors.white,
            onTap: () {
              ///切换语言并保存语言至本地
              String? locale = SharedPreferenceUtil.getString(
                  BilibiliSharedPreference.locale);
              if (locale == 'zh') {
                Get.updateLocale(const Locale('en', 'US'));
                SharedPreferenceUtil.setString(
                    BilibiliSharedPreference.locale, 'en');
              } else {
                Get.updateLocale(const Locale('zh', 'CN'));
                SharedPreferenceUtil.setString(
                    BilibiliSharedPreference.locale, 'zh');
              }
            },
            label: '切换语言',
            child: Icon(
              Icons.ac_unit_sharp,
              size: 10.h,
            ),
          ),
        ],
      ),
    );
  }
}
